/**
 * 仪表盘数据集成脚本
 * 用于替换前端静态数据，调用后端API获取用户个性化数据
 */

class DashboardAPI {
    constructor() {
        this.baseURL = 'http://localhost:8080';
        this.token = this.getToken();
    }

    /**
     * 获取JWT令牌
     */
    getToken() {
        // 从localStorage或sessionStorage获取token
        return localStorage.getItem('token') || sessionStorage.getItem('token');
    }

    /**
     * 通用API请求方法
     */
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.token}`,
                ...options.headers
            },
            ...options
        };

        try {
            const response = await fetch(url, config);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    /**
     * 获取完整仪表盘数据
     */
    async getDashboardData() {
        return await this.request('/dashboard/data');
    }

    /**
     * 获取用户摘要
     */
    async getUserSummary() {
        return await this.request('/dashboard/summary');
    }

    /**
     * 获取项目统计
     */
    async getProjectStatistics() {
        return await this.request('/dashboard/projects');
    }

    /**
     * 获取任务统计
     */
    async getTaskStatistics() {
        return await this.request('/dashboard/tasks');
    }

    /**
     * 获取资金统计
     */
    async getFundingStatistics() {
        return await this.request('/dashboard/funding');
    }

    /**
     * 获取发表论文统计
     */
    async getPublicationStatistics() {
        return await this.request('/dashboard/publications');
    }

    /**
     * 获取图表数据
     */
    async getChartData() {
        return await this.request('/dashboard/charts');
    }

    /**
     * 获取最近活动
     */
    async getRecentActivities() {
        return await this.request('/dashboard/activities');
    }
}

/**
 * 仪表盘数据管理器
 */
class DashboardManager {
    constructor() {
        this.api = new DashboardAPI();
        this.cache = new Map();
        this.cacheTimeout = 5 * 60 * 1000; // 5分钟缓存
    }

    /**
     * 获取缓存数据
     */
    getFromCache(key) {
        const cached = this.cache.get(key);
        if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
            return cached.data;
        }
        return null;
    }

    /**
     * 设置缓存数据
     */
    setCache(key, data) {
        this.cache.set(key, {
            data,
            timestamp: Date.now()
        });
    }

    /**
     * 获取仪表盘数据（带缓存）
     */
    async getDashboardData() {
        const cacheKey = 'dashboard_data';
        let data = this.getFromCache(cacheKey);
        
        if (!data) {
            try {
                data = await this.api.getDashboardData();
                this.setCache(cacheKey, data);
            } catch (error) {
                console.error('获取仪表盘数据失败:', error);
                return this.getFallbackData();
            }
        }
        
        return data;
    }

    /**
     * 获取备用数据（当API失败时）
     */
    getFallbackData() {
        return {
            userSummary: {
                fullName: '用户',
                department: '未知部门',
                role: 'USER',
                status: 'IDLE',
                totalProjects: 0,
                totalTasks: 0,
                totalPublications: 0
            },
            projectStatistics: {
                totalProjects: 0,
                activeProjects: 0,
                completedProjects: 0,
                pendingProjects: 0,
                onHoldProjects: 0,
                totalBudget: 0,
                recentProjects: []
            },
            taskStatistics: {
                totalTasks: 0,
                todoTasks: 0,
                inProgressTasks: 0,
                completedTasks: 0,
                overdueTasks: 0,
                urgentTasks: 0,
                upcomingTasks: []
            },
            fundingStatistics: {
                totalIncome: 0,
                totalExpense: 0,
                balance: 0,
                transactionCount: 0,
                monthlyTrend: []
            },
            publicationStatistics: {
                totalPublications: 0,
                thisYearPublications: 0,
                yearlyTrend: [],
                recentPublications: []
            },
            recentActivities: [],
            chartData: {
                projectStatusChart: [],
                taskPriorityChart: [],
                monthlyFundingChart: [],
                publicationTrendChart: []
            }
        };
    }

    /**
     * 更新仪表盘UI
     */
    async updateDashboard() {
        try {
            const data = await this.getDashboardData();
            
            // 更新统计卡片
            this.updateStatCards(data);
            
            // 更新图表
            this.updateCharts(data);
            
            // 更新最近活动
            this.updateRecentActivities(data);
            
            console.log('仪表盘数据更新成功');
        } catch (error) {
            console.error('更新仪表盘失败:', error);
        }
    }

    /**
     * 更新统计卡片
     */
    updateStatCards(data) {
        const { userSummary, projectStatistics, taskStatistics, publicationStatistics } = data;
        
        // 更新项目数量
        this.updateElement('.project-count', projectStatistics.totalProjects || 0);
        
        // 更新任务数量
        this.updateElement('.task-count', taskStatistics.totalTasks || 0);
        
        // 更新发表论文数量
        this.updateElement('.publication-count', publicationStatistics.totalPublications || 0);
        
        // 更新完成率（基于已完成任务的百分比）
        const completionRate = taskStatistics.totalTasks > 0 
            ? Math.round((taskStatistics.completedTasks / taskStatistics.totalTasks) * 100)
            : 0;
        this.updateElement('.completion-rate', `${completionRate}%`);
    }

    /**
     * 更新DOM元素
     */
    updateElement(selector, value) {
        const element = document.querySelector(selector);
        if (element) {
            element.textContent = value;
        }
    }

    /**
     * 更新图表
     */
    updateCharts(data) {
        const { chartData } = data;
        
        // 如果有图表库（如ECharts），在这里更新图表
        if (window.echarts) {
            this.updateECharts(chartData);
        }
    }

    /**
     * 更新ECharts图表
     */
    updateECharts(chartData) {
        // 项目状态饼图
        const projectChart = echarts.getInstanceByDom(document.getElementById('project-status-chart'));
        if (projectChart && chartData.projectStatusChart) {
            projectChart.setOption({
                series: [{
                    data: chartData.projectStatusChart
                }]
            });
        }

        // 任务优先级图表
        const taskChart = echarts.getInstanceByDom(document.getElementById('task-priority-chart'));
        if (taskChart && chartData.taskPriorityChart) {
            taskChart.setOption({
                series: [{
                    data: chartData.taskPriorityChart
                }]
            });
        }
    }

    /**
     * 更新最近活动
     */
    updateRecentActivities(data) {
        const { recentActivities } = data;
        const container = document.querySelector('.recent-activities');
        
        if (container && recentActivities) {
            container.innerHTML = recentActivities.map(activity => `
                <div class="activity-item">
                    <div class="activity-type">${activity.type}</div>
                    <div class="activity-description">${activity.description}</div>
                    <div class="activity-time">${activity.timestamp}</div>
                </div>
            `).join('');
        }
    }

    /**
     * 定时刷新数据
     */
    startAutoRefresh(interval = 5 * 60 * 1000) { // 默认5分钟
        setInterval(() => {
            this.cache.clear(); // 清除缓存，强制重新获取数据
            this.updateDashboard();
        }, interval);
    }
}

// 全局实例
window.dashboardManager = new DashboardManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化仪表盘
    window.dashboardManager.updateDashboard();
    
    // 开始自动刷新
    window.dashboardManager.startAutoRefresh();
    
    console.log('仪表盘集成脚本已加载');
});

// 导出供其他脚本使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { DashboardAPI, DashboardManager };
}
